#include "stdafx.h"
#include "MyFileDialog.h"
#include <shlwapi.h>

#pragma comment(lib,"Shlwapi.lib")

#define _countof(array) (sizeof(array)/sizeof(array[0]))
#define GCT_VALID (GCT_LFNCHAR|GCT_SHORTCHAR|GCT_SEPARATOR)

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

#ifdef CWinApp
#undef CWinApp
#endif

IMPLEMENT_DYNAMIC(CMyFileDialog, CFileDialog)

CMyFileDialog::CMyFileDialog(BOOL bOpenFileDialog, LPCTSTR lpszDefExt, LPCTSTR lpszFileName,
		DWORD dwFlags, LPCTSTR lpszFilter, CWnd* pParentWnd, LPCTSTR lpszFile) :
		CFileDialog(bOpenFileDialog, lpszDefExt, lpszFileName, dwFlags, lpszFilter, pParentWnd)
{
		m_ofn.lStructSize = 88;
		m_ofn.nMaxFile = MAX_PATH*64;
		m_ofn.lpstrFile = new TCHAR[MAX_PATH*64];
		memset(m_ofn.lpstrFile, 0, MAX_PATH*64);
		m_strEntry = lpszFileName;

		CString string = lpszFile;
		if (string.GetLength())
		{
			lstrcpyn(m_szFileName, string, _countof(m_szFileName));
			int nCount = min(string.GetLength(), _countof(m_szFileName));
			for (int i = 0; i < nCount; i++)
			{
				UINT nType = ::PathGetCharType(m_szFileName[i]);
				if ((nType & GCT_VALID) == 0)
				{
					m_szFileName[0] = '\0';
					string.Empty();
					break;
				}
			}
		}

		if (string.IsEmpty())
		{
			CWinApp* pApp = AfxGetApp();
			string = pApp->GetProfileString(_T("Recent File Path"), lpszFileName);
			lstrcpyn(m_szFileName, string, _countof(m_szFileName));
			int nCount = min(string.GetLength(), _countof(m_szFileName));
			for (int i = 0; i < nCount; i++)
			{
				UINT nType = ::PathGetCharType(m_szFileName[i]);
				if ((nType & GCT_VALID) == 0)
				{
					m_szFileName[0] = '\0';
					break;
				}
			}
		}		
}


BEGIN_MESSAGE_MAP(CMyFileDialog, CFileDialog)
	//{{AFX_MSG_MAP(CMyFileDialog)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

CMyFileDialog::~CMyFileDialog()
{	
	CString str = GetPathName();
	if (str.GetLength())
	{
		CWinApp* pApp = AfxGetApp();
		pApp->WriteProfileString(_T("Recent File Path"), m_strEntry, str);
	}

	delete [] m_ofn.lpstrFile;
}

